"""
RagFlow 客户端 GUI 线程模块
"""

from PySide6.QtCore import Signal, QThread

from ragflow_client.api import RagFlowAPI
from ragflow_client.config import RagFlowConfig
from ragflow_client.service import RagFlowService
from ragflow_client.utils.file_util import get_files


class WorkerThread(QThread):
    """工作线程基类"""
    finished = Signal(bool, str)
    progress = Signal(int)
    
    def __init__(self):
        super().__init__()
        self.cancel_flag = False
    
    def cancel(self):
        """取消操作"""
        self.cancel_flag = True


class ConnectionTestThread(WorkerThread):
    """连接测试线程"""
    
    def __init__(self, config: RagFlowConfig):
        super().__init__()
        self.config = config
    
    def run(self):
        """运行线程"""
        try:
            api = RagFlowAPI(self.config)
            status, msg = api.check_connection()
            self.finished.emit(status, msg)
        except Exception as e:
            self.finished.emit(False, str(e))


class UploadFilesThread(WorkerThread):
    """文件上传线程"""
    status_update = Signal(str)
    upload_result = Signal(int, int)  # 成功数量，失败数量
    
    def __init__(self, config: RagFlowConfig, batch_size: int):
        super().__init__()
        self.config = config
        self.batch_size = batch_size
    
    def run(self):
        """运行线程"""
        try:
            service = RagFlowService(self.config)
            files = get_files(self.config.doc_dir, self.config.doc_suffix)
            
            if not files:
                self.status_update.emit("没有找到符合条件的文件")
                self.finished.emit(True, "没有找到符合条件的文件")
                return
            
            self.status_update.emit(f"找到 {len(files)} 个文件")
            
            # 分批上传
            batches = [files[i:i + self.batch_size] for i in range(0, len(files), self.batch_size)]
            
            success_count = 0
            failed_count = 0
            
            for i, batch in enumerate(batches):
                # 检查是否取消
                if self.cancel_flag:
                    self.status_update.emit("上传已取消")
                    self.finished.emit(False, "上传已取消")
                    return
                
                # 更新进度
                progress = int((i / len(batches)) * 100)
                self.progress.emit(progress)
                
                # 更新状态
                self.status_update.emit(f"正在上传批次 {i+1}/{len(batches)}...")
                
                # 上传批次
                status, result = service.api.upload_files(batch)
                
                if status:
                    success_count += len(batch)
                else:
                    failed_count += len(batch)
            
            # 更新进度
            self.progress.emit(100)
            
            # 发送结果
            self.upload_result.emit(success_count, failed_count)
            self.finished.emit(True, f"上传完成，成功: {success_count}，失败: {failed_count}")
            
        except Exception as e:
            self.finished.emit(False, str(e))